home *** CD-ROM | disk | FTP | other *** search
/ Internet Surfer 2.0 / Internet Surfer 2.0 (Wayzata Technology) (1996).iso / pc / textfile / faqs / lisp_faq / part3 < prev    next >
Encoding:
Internet Message Format  |  1992-12-26  |  32.2 KB

  1. Xref: bloom-picayune.mit.edu comp.lang.lisp:8751 news.answers:4561
  2. Path: bloom-picayune.mit.edu!enterpoop.mit.edu!spool.mu.edu!uunet!ogicse!das-news.harvard.edu!cantaloupe.srv.cs.cmu.edu!crabapple.srv.cs.cmu.edu!mkant
  3. From: mkant+@cs.cmu.edu (Mark Kantrowitz)
  4. Newsgroups: comp.lang.lisp,news.answers
  5. Subject: FAQ: Lisp Frequently Asked Questions 3/6 [Monthly posting]
  6. Summary: Common Pitfalls
  7. Message-ID: <lisp-faq-3.text_724237304@cs.cmu.edu>
  8. Date: 13 Dec 92 09:02:09 GMT
  9. Article-I.D.: cs.lisp-faq-3.text_724237304
  10. Expires: Tue, 26 Jan 1993 09:01:44 GMT
  11. Sender: news@cs.cmu.edu (Usenet News System)
  12. Reply-To: lisp-faq@think.com
  13. Followup-To: poster
  14. Organization: School of Computer Science, Carnegie Mellon
  15. Lines: 707
  16. Approved: news-answers-request@MIT.Edu
  17. Supersedes: <lisp-faq-3.text_721645325@cs.cmu.edu>
  18. Nntp-Posting-Host: a.gp.cs.cmu.edu
  19.  
  20. Archive-name: lisp-faq/part3
  21. Last-Modified: Thu Nov  5 19:30:40 1992 by Mark Kantrowitz
  22. Version: 1.27
  23.  
  24. ;;; ****************************************************************
  25. ;;; Answers to Frequently Asked Questions about Lisp ***************
  26. ;;; ****************************************************************
  27. ;;; Written by Mark Kantrowitz and Barry Margolin
  28. ;;; lisp-faq-3.text -- 32488 bytes
  29.  
  30. This post contains Part 3 of the Lisp FAQ.
  31.  
  32. If you think of questions that are appropriate for this FAQ, or would
  33. like to improve an answer, please send email to us at lisp-faq@think.com.
  34.  
  35. This section contains a list of common pitfalls. Pitfalls are aspects
  36. of Common Lisp which are non-obvious to new programmers and often
  37. seasoned programmers as well.
  38.  
  39. Common Pitfalls (Part 3):
  40.  
  41.   [3-0]  Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR
  42.          instead of BAR?  
  43.   [3-1]  Why can't it deduce from (READ-FROM-STRING "foobar" :START 3)
  44.          that the intent is to specify the START keyword parameter
  45.          rather than the EOF-ERROR-P and EOF-VALUE optional parameters?   
  46.   [3-2]  Why can't I apply #'AND and #'OR?
  47.   [3-3]  I used a destructive function (e.g. DELETE, SORT), but it
  48.          didn't seem to work.  Why? 
  49.   [3-4]  After I NREVERSE a list, it's only one element long.  After I
  50.          SORT a list, it's missing things.  What happened? 
  51.   [3-5]  Why does (READ-LINE) return "" immediately instead of waiting
  52.          for me to type a line?  
  53.   [3-6]  I typed a form to the read-eval-print loop, but nothing happened. Why?
  54.   [3-7]  DEFMACRO doesn't seem to work.
  55.          When I compile my file, LISP warns me that my macros are undefined
  56.          functions, or complains "Attempt to call <function> which is 
  57.          defined as a macro.
  58.   [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  59.   [3-9]  Closures don't seem to work properly when referring to the
  60.          iteration variable in DOLIST, DOTIMES and DO.
  61.   [3-10] What is the difference between FUNCALL and APPLY?
  62.   [3-11] Miscellaneous things to consider when debugging code.
  63.   [3-12] When is it right to use EVAL?
  64.   [3-13] Why does my program's behavior change each time I use it?
  65.   [3-14] When producing formatted output in Lisp, where should you put the
  66.          newlines (e.g., before or after the line, FRESH-LINE vs TERPRI,
  67.          ~& vs ~% in FORMAT)?
  68.   [3-15] I'm using DO to do some iteration, but it doesn't terminate. 
  69.  
  70. Search for [#] to get to question number # quickly.
  71.  
  72. ----------------------------------------------------------------
  73. [3-0] Why does (READ-FROM-STRING "foobar" :START 3) return FOOBAR instead 
  74.       of BAR?
  75.  
  76. READ-FROM-STRING is one of the rare functions that takes both &OPTIONAL and
  77. &KEY arguments:
  78.  
  79.        READ-FROM-STRING string &OPTIONAL eof-error-p eof-value 
  80.                                &KEY :start :end :preserve-whitespace
  81.  
  82. When a function takes both types of arguments, all the optional
  83. arguments must be specified explicitly before any of the keyword
  84. arguments may be specified.  In the example above, :START becomes the
  85. value of the optional EOF-ERROR-P parameter and 3 is the value of the
  86. optional EOF-VALUE parameter.
  87.      
  88. ----------------------------------------------------------------
  89. [3-1] Why can't it deduce from (READ-FROM-STRING "foobar" :START 3) that
  90.       the intent is to specify the START keyword parameter rather than
  91.       the EOF-ERROR-P and EOF-VALUE optional parameters?
  92.  
  93. In Common Lisp, keyword symbols are first-class data objects.  Therefore,
  94. they are perfectly valid values for optional parameters to functions.
  95. There are only four functions in Common Lisp that have both optional and
  96. keyword parameters (they are PARSE-NAMESTRING, READ-FROM-STRING,
  97. WRITE-LINE, and WRITE-STRING), so it's probably not worth adding a
  98. nonorthogonal kludge to the language just to make these functions slightly
  99. less confusing; unfortunately, it's also not worth an incompatible change
  100. to the language to redefine those functions to use only keyword arguments.
  101.      
  102. ----------------------------------------------------------------
  103. [3-2] Why can't I apply #'AND and #'OR?
  104.  
  105. Here's the simple, but not necessarily satisfying, answer: AND and OR are
  106. macros, not functions; APPLY and FUNCALL can only be used to invoke
  107. functions, not macros and special operators.
  108.  
  109. OK, so what's the *real* reason?  The reason that AND and OR are macros
  110. rather than functions is because they implement control structure in
  111. addition to computing a boolean value.  They evaluate their subforms
  112. sequentially from left/top to right/bottom, and stop evaluating subforms as
  113. soon as the result can be determined (in the case of AND, as soon as a
  114. subform returns NIL; in the case of OR, as soon as one returns non-NIL);
  115. this is referred to as "short circuiting" in computer language parlance.
  116. APPLY and FUNCALL, however, are ordinary functions; therefore, their
  117. arguments are evaluated automatically, before they are called.  Thus, were
  118. APPLY able to be used with #'AND, the short-circuiting would be defeated.
  119.  
  120. Perhaps you don't really care about the short-circuiting, and simply want
  121. the functional, boolean interpretation.  While this may be a reasonable
  122. interpretation of trying to apply AND or OR, it doesn't generalize to other
  123. macros well, so there's no obvious way to have the Lisp system "do the
  124. right thing" when trying to apply macros.  The only function associated
  125. with a macro is its expander function; this function accepts and returns
  126. and form, so it cannot be used to compute the value.
  127.  
  128. The Common Lisp functions EVERY and SOME can be used to get the
  129. functionality you intend when trying to apply #'AND and #'OR.  For
  130. instance, the erroneous form:
  131.  
  132.    (apply #'and *list*)
  133.  
  134. can be translated to the correct form:
  135.  
  136.    (every #'identity *list*)
  137.  
  138. ----------------------------------------------------------------
  139. [3-3] I used a destructive function (e.g. DELETE, SORT), but it didn't seem to
  140.       work.  Why?
  141.  
  142. I assume you mean that it didn't seem to modify the original list.  There
  143. are several possible reasons for this.  First, many destructive functions
  144. are not *required* to modify their input argument, merely *allowed* to; in
  145. some cases, the implementation may determine that it is more efficient to
  146. construct a new result than to modify the original (this may happen in Lisp
  147. systems that use "CDR coding", where RPLACD may have to turn a CDR-NEXT or
  148. CDR-NIL cell into a CDR-NORMAL cell), or the implementor may simply not
  149. have gotten around to implementing the destructive version in a truly
  150. destructive manner.  Another possibility is that the nature of the change
  151. that was made involves removing elements from the front of a list; in this
  152. case, the function can simply return the appropriate tail of the list,
  153. without actually modifying the list. And example of this is:
  154.      
  155.    (setq *a* (list 3 2 1))
  156.    (delete 3 *a*) => (2 1)
  157.    *a* => (3 2 1)
  158.  
  159. Similarly, when one sorts a list, SORT may destructively rearrange the
  160. pointers (cons cells) that make up the list. SORT then returns the cons
  161. cell that now heads the list; the original cons cell could be anywhere in
  162. the list. The value of any variable that contained the original head of the
  163. list hasn't changed, but the contents of that cons cell have changed
  164. because SORT is a destructive function:
  165.  
  166.    (setq *a* (list 2 1 3))
  167.    (sort *a* #'<) => (1 2 3)
  168.    *a* => (2 3)     
  169.  
  170. In both cases, the remedy is the same: store the result of the
  171. function back into the place whence the original value came, e.g.
  172.  
  173.    (setq *a* (delete 3 *a*))
  174.    *a* => (2 1)
  175.  
  176. Why don't the destructive functions do this automatically?  Recall that
  177. they are just ordinary functions, and all Lisp functions are called by
  178. value.  Therefore, these functions do not know where the lists they are
  179. given came from; they are simply passed the cons cell that represents the
  180. head of the list. Their only obligation is to return the new cons cell that
  181. represents the head of the list.
  182.  
  183. One thing to be careful about when doing this is that the original list
  184. might be referenced from multiple places, and all of these places may need
  185. to be updated.  For instance:
  186.  
  187.    (setq *a* (list 3 2 1))
  188.    (setq *b* *a*)
  189.    (setq *a* (delete 3 *a*))
  190.    *a* => (2 1)
  191.    *b* => (3 2 1) ; *B* doesn't "see" the change
  192.    (setq *a* (delete 1 *a*))
  193.    *a* => (2)
  194.    *b* => (3 2) ; *B* sees the change this time, though
  195.  
  196. One may argue that destructive functions could do what you expect by
  197. rearranging the CARs of the list, shifting things up if the first element
  198. is being deleted, as they are likely to do if the argument is a vector
  199. rather than a list.  In many cases they could do this, although it would
  200. clearly be slower.  However, there is one case where this is not possible:
  201. when the argument or value is NIL, and the value or argument, respectively,
  202. is not.  It's not possible to transform the object referenced from the
  203. original cell from one data type to another, so the result must be stored
  204. back.  Here are some examples:
  205.  
  206.    (setq *a* (list 3 2 1))
  207.    (delete-if #'numberp *a) => NIL
  208.    *a* => (3 2 1)
  209.    (setq *a* nil *b* '(1 2 3))
  210.    (nconc *a* *b*) => (1 2 3)
  211.    *a* => NIL
  212.  
  213. The names of most destructure functions (except for sort, delete,
  214. rplaca, rplacd, and setf of accessor functions) have the prefix N.
  215.  
  216. In summary, the two common problems to watch out for when using
  217. destructive functions are:
  218.  
  219.    1. Forgetting to store the result back. Even though the list
  220.       is modified in place, it is still necessary to store the
  221.       result of the function back into the original location, e.g.,
  222.            (setq foo (delete 'x foo))
  223.  
  224.       If the original list was stored in multiple places, you may
  225.       need to store it back in all of them, e.g.
  226.            (setq bar foo)
  227.            ...
  228.            (setq foo (delete 'x foo))
  229.            (setq bar foo)
  230.  
  231.    2. Sharing structure that gets modified. If it is important
  232.       to preserve the shared structure, then you should either
  233.       use a nondestructive operation or copy the structure first
  234.       using COPY-LIST or COPY-TREE.
  235.            (setq bar (cdr foo))
  236.            ...
  237.            (setq foo (sort foo #'<))
  238.            ;;; now it's not safe to use BAR
  239.  
  240. Note that even nondestructive functions, such as REMOVE, and UNION,
  241. can return a result which shares structure with an argument. 
  242. Nondestructive functions don't necessarily copy their arguments; they
  243. just don't modify them.
  244.      
  245. ----------------------------------------------------------------
  246. [3-4] After I NREVERSE a list, it's only one element long.  After I SORT
  247.       a list, it's missing things.  What happened?
  248.  
  249. These are particular cases of the previous question.  Many NREVERSE and
  250. SORT implementations operate by rechaining all the CDR links in the list's
  251. backbone, rather than by replacing the CARs.  In the case of NREVERSE, this
  252. means that the cons cell that was originally first in the list becomes the
  253. last one.  As in the last question, the solution is to store the result
  254. back into the original location.
  255.      
  256. ----------------------------------------------------------------
  257. [3-5] Why does (READ-LINE) return "" immediately instead of waiting for
  258.       me to type a line?
  259.  
  260. Many Lisp implementations on line-buffered systems do not discard the
  261. newline that the user must type after the last right parenthesis in order
  262. for the line to be transmitted from the OS to Lisp.  Lisp's READ function
  263. returns immediately after seeing the matching ")" in the stream.  When
  264. READLINE is called, it sees the next character in the stream, which is a
  265. newline, so it returns an empty line.  If you were to type "(read-line)This
  266. is a test" the result would be "This is a test".
  267.  
  268. The simplest solution is to use (PROGN (CLEAR-INPUT) (READ-LINE)).  This
  269. discards the buffered newline before reading the input.  However, it would
  270. also discard any other buffered input, as in the "This is a test" example
  271. above; some implementation also flush the OS's input buffers, so typeahead
  272. might be thrown away.
  273.  
  274. ----------------------------------------------------------------
  275. [3-6] I typed a form to the read-eval-print loop, but nothing happened. Why?
  276.  
  277. There's not much to go on here, but a common reason is that you haven't
  278. actually typed a complete form.  You may have typed a doublequote, vertical
  279. bar, "#|" comment beginning, or left parenthesis that you never matched
  280. with another doublequote, vertical bar, "|#", or right parenthesis,
  281. respectively.  Try typing a few right parentheses followed by Return.
  282.  
  283. ----------------------------------------------------------------
  284. [3-7]  DEFMACRO doesn't seem to work. 
  285.        When I compile my file, LISP warns me that my macros are undefined
  286.        functions, or complains "Attempt to call <function> which is 
  287.        defined as a macro.
  288.  
  289. When you evaluate a DEFMACRO form or proclaim a function INLINE, it
  290. doesn't go back and update code that was compiled under the old
  291. definition. When redefining a macro, be sure to recompile any
  292. functions that use the macro. Also be sure that the macros used in a
  293. file are defined before any forms in the same file that use them.
  294.  
  295. Certain forms, including LOAD, SET-MACRO-CHARACTER, and
  296. REQUIRE, are not normally evaluated at compile time. Common Lisp
  297. requires that macros defined in a file be used when compiling later
  298. forms in the file. If a Lisp doesn't follow the standard, it may be
  299. necessary to wrap an EVAL-WHEN form around the macro definition.
  300.  
  301. Most often the "macro was previously called as a function" problem
  302. occurs when files were compiled/loaded in the wrong order. For
  303. example, developers may add the definition to one file, but use it in
  304. a file which is compiled/loaded before the definition. To work around
  305. this problem, one can either fix the modularization of the system, or
  306. manually recompile the files containing the forward references to macros.
  307.  
  308. Also, if your macro calls functions at macroexpand time, those functions
  309. may need to be in an EVAL-WHEN. For example,
  310.  
  311.     (defun some-function (x)
  312.       x)
  313.  
  314.     (defmacro some-macro (y)
  315.       (let ((z (some-function y)))
  316.         `(print ',z)))
  317.  
  318. If the macros are defined in a file you require, make sure your
  319. require or load statement is in an appropriate EVAL-WHEN. Many people
  320. avoid all this nonsense by making sure to load all their files before
  321. compiling them, or use a system facility (or just a script file) that
  322. loads each file before compiling the next file in the system.
  323.  
  324. ----------------------------------------------------------------
  325. [3-8]  Name conflict errors are driving me crazy! (EXPORT, packages)
  326.  
  327. If a package tries to export a symbol that's already defined, it will
  328. report an error. You probably tried to use a function only to discover
  329. that you'd forgotten to load its file. The failed attempt at using the
  330. function caused its symbol to be interned. So now, when you try to
  331. load the file, you get a conflict. Unfortunately, understanding and
  332. correcting the code which caused the export problem doesn't make those
  333. nasty error messages go away. That symbol is still interned where it
  334. shouldn't be. Use unintern to remove the symbol from a package before
  335. reloading the file. Also, when giving arguments to REQUIRE or package
  336. functions, use strings or keywords, not symbols: (find-package "FOO"),
  337. (find-package :foo). 
  338.  
  339. A sometimes useful technique is to rename (or delete) a package
  340. that is "too messed up".  Then you can reload the relevant files
  341. into a "clean" package.
  342.  
  343. ----------------------------------------------------------------
  344. [3-9]  Closures don't seem to work properly when referring to the
  345.        iteration variable in DOLIST, DOTIMES and DO.
  346.  
  347. DOTIMES, DOLIST, and DO all use assignment instead of binding to
  348. update the value of the iteration variables. So something like
  349.    
  350.    (let ((l nil))
  351.      (dotimes (n 10)
  352.        (push #'(lambda () n)
  353.          l)))
  354.  
  355. will produce 10 closures over the same value of the variable N.
  356. ----------------------------------------------------------------
  357. [3-10] What is the difference between FUNCALL and APPLY?
  358.  
  359. FUNCALL is useful when the programmer knows the length of the argument
  360. list, but the function to call is either computed or provided as a
  361. parameter.  For instance, a simple implementation of MEMBER-IF (with
  362. none of the fancy options) could be written as:
  363.  
  364. (defun member-if (predicate list)
  365.   (do ((tail list (cdr tail)))
  366.       ((null tail))
  367.    (when (funcall predicate (car tail))
  368.      (return-from member-if tail))))
  369.  
  370. The programmer is invoking a caller-supplied function with a known
  371. argument list.
  372.  
  373. APPLY is needed when the argument list itself is supplied or computed.
  374. Its last argument must be a list, and the elements of this list become
  375. individual arguments to the function.  This frequently occurs when a
  376. function takes keyword options that will be passed on to some other
  377. function, perhaps with application-specific defaults inserted.  For
  378. instance:
  379.  
  380. (defun open-for-output (pathname &rest open-options)
  381.   (apply #'open pathname :direction :output open-options))
  382.  
  383. FUNCALL could actually have been defined using APPLY:
  384.  
  385. (defun funcall (function &rest arguments)
  386.   (apply function arguments))
  387.  
  388. ----------------------------------------------------------------
  389. [3-11] Miscellaneous things to consider when debugging code.
  390.  
  391. This question lists a variety of problems to watch out for when
  392. debugging code. This is sort of a catch-all question for problems too
  393. small to merit a question of their own. See also question [1-2] for
  394. some other common problems.
  395.  
  396. Functions:
  397.  
  398.   * (flet ((f ...)) (eq #'f #'f)) can return false.
  399.  
  400.   * The function LIST-LENGTH is not a faster, list-specific version
  401.     of the sequence function LENGTH.  It is list-specific, but it's
  402.     slower than LENGTH because it can handle circular lists.
  403.  
  404.   * Don't confuse the use of LISTP and CONSP. CONSP tests for the
  405.     presence of a cons cell, but will return NIL when called on NIL.
  406.     LISTP could be defined as (defun listp (x) (or (null x) (consp x))).
  407.  
  408.   * Use the right test for equality: 
  409.         EQ      tests if the objects are identical -- numbers with the
  410.                 same value need not be EQ, nor are two similar lists
  411.                 necessarily EQ. Similarly for characters and strings.
  412.                 For instance, (let ((x 1)) (eq x x)) is not guaranteed
  413.                 to return T.
  414.         EQL     Like EQ, but is also true if the arguments are numbers
  415.                 of the same type with the same value or character objects
  416.                 representing the same character. (eql -0.0 0.0) is not
  417.                 guaranteed to return T.
  418.         EQUAL   Tests if the arguments are structurally isomorphic, using
  419.                 EQUAL to compare components that conses, arrays, strings
  420.                 or pathnames, and EQ for all other data objects
  421.                 (except for numbers and characters, which are compared
  422.                 using EQL). 
  423.         EQUALP  Like EQUAL, but ignores type differences when comparing 
  424.                 numbers and case differences when comparing characters.
  425.         =       Compares the values of two numbers even if they are of
  426.                 different types.
  427.         CHAR=   Case-sensitive comparison of characters.
  428.         CHAR-EQUAL      Case-insensitive comparison of characters.
  429.         STRING= Compares two strings, checking if they are identical.
  430.                 It is case sensitive.
  431.         STRING-EQUAL  Like STRING=, but case-insensitive.
  432.  
  433.   * Some destructive functions that you think would modify CDRs might
  434.     modify CARs instead.  (E.g., NREVERSE.)
  435.  
  436.   * READ-FROM-STRING has some optional arguments before the
  437.     keyword parameters.  If you want to supply some keyword
  438.     arguments, you have to give all of the optional ones too.
  439.  
  440.   * If you use the function READ-FROM-STRING, you should probably bind
  441.     *READ-EVAL* to NIL. Otherwise an unscrupulous user could cause a
  442.     lot of damage by entering 
  443.         #.(shell "cd; rm -R *")
  444.     at a prompt.
  445.  
  446.   * Only functional objects can be funcalled in CLtL2, so a lambda
  447.     expression '(lambda (..) ..) is no longer suitable. Use
  448.     #'(lambda (..) ..) instead. If you must use '(lambda (..) ..),
  449.     coerce it to type FUNCTION first using COERCE.
  450.  
  451. Methods:
  452.  
  453.   * PRINT-OBJECT methods can make good code look buggy. If there is a
  454.     problem with the PRINT-OBJECT methods for one of your classes, it
  455.     could make it seem as though there were a problem with the object.
  456.     It can be very annoying to go chasing through your code looking for
  457.     the cause of the wrong value, when the culprit is just a bad
  458.     PRINT-OBJECT method.
  459.  
  460. Initialization:
  461.  
  462.   * Don't count on array elements being initialized to NIL, if you don't
  463.     specify an :initial-element argument to MAKE-ARRAY. For example,
  464.          (make-array 10) => #(0 0 0 0 0 0 0 0 0 0)
  465.  
  466. Iteration vs closures:
  467.  
  468.   * DO and DO* update the iteration variables by assignment; DOLIST and
  469.     DOTIMES are allowed to use assignment (rather than a new binding).
  470.     (All CLtL1 says of DOLIST and DOTIMES is that the variable "is
  471.     bound" which has been taken as _not_ implying that there will be
  472.     separate bindings for each iteration.) 
  473.  
  474.     Consequently, if you make closures over an iteration variable
  475.     in separate iterations they may nonetheless be closures over
  476.     the same variable and hence will all refer to the same value
  477.     -- whatever value the variable was given last.  For example,
  478.         (let ((fns '()))
  479.           (do ((x '(1 2) (cdr x)))
  480.               ((null x))
  481.             (push #'(lambda () x)
  482.                   fns))
  483.           (mapcar #'funcall (reverse fns)))
  484.     returns (nil nil), not (1 2), not even (2 2). Thus 
  485.          (let ((l nil)) 
  486.            (dolist (a '(1 2 3) l) 
  487.              (push #'(lambda () a)
  488.                    l)))
  489.     returns a list of three closures closed over the same bindings, whereas
  490.          (mapcar #'(lambda (a) #'(lambda () a)) '(1 2 3))
  491.     returns a list of closures over distinct bindings.
  492.  
  493. Defining Variables and Constants:
  494.  
  495.   * (defvar var init) assigns to the variable only if it does not
  496.     already have a value.  So if you edit a DEFVAR in a file and
  497.     reload the file only to find that the value has not changed,
  498.     this is the reason.  (Use DEFPARAMETER if you want the value
  499.     to change upon reloading.) DEFVAR is used to declare a variable
  500.     that is changed by the program; DEFPARAMETER is used to declare
  501.     a variable that is normally constant, but which can be changed
  502.     to change the functioning of a program.
  503.  
  504.   * DEFCONSTANT has several potentially unexpected properties:
  505.  
  506.      - Once a name has been declared constant, it cannot be used a
  507.        the name of a local variable (lexical or special) or function
  508.        parameter.  Really.  See page 87 of CLtL2.
  509.  
  510.      - A DEFCONSTANT cannot be re-evaluated (eg, by reloading the
  511.        file in which it appears) unless the new value is EQL to the
  512.        old one.  Strictly speaking, even that may not be allowed.
  513.        (DEFCONSTANT is "like DEFPARAMETER" and hence does an
  514.        assignment, which is not allowed if the name has already
  515.        been declared constant by DEFCONSTANT.)
  516.  
  517.        Note that this makes it difficult to use anything other
  518.        than numbers, symbols, and characters as constants.       
  519.  
  520.      - When compiling (DEFCONSTANT name form) in a file, the form
  521.        may be evaluated at compile-time, load-time, or both.  
  522.  
  523.        (You might think it would be evaluated at compile-time and
  524.        the _value_ used to obtain the object at load-time, but it
  525.        doesn't have to work that way.)
  526.  
  527. Declarations:
  528.  
  529.   * You often have to declare the result type to get the most
  530.     efficient arithmetic.  Eg, 
  531.  
  532.        (the fixnum (+ (the fixnum e1) (the fixnum e2)))
  533.  
  534.      rather than
  535.  
  536.        (+ (the fixnum e1) (the fixnum e2))
  537.  
  538.   * Declaring the iteration variable of a DOTIMES to have type FIXNUM
  539.     does not guarantee that fixnum arithmetic will be used.  That is,
  540.     implementations that use fixnum-specific arithmetic in the presence
  541.     of appropriate declaration may not think _this_ declaration is
  542.     sufficient.  It may help to declare that the limit is also a
  543.     fixnum, or you may have to write out the loop as a DO and add
  544.     appropriate declarations for each operation involved.
  545.  
  546. FORMAT related errors:
  547.  
  548.   * When printing messages about files, filenames like foo~ (a GNU-Emacs
  549.     backup file) may cause problems with poorly coded FORMAT control
  550.     strings.
  551.  
  552.   * Beware of using an ordinary string as the format string,
  553.     i.e., (format t string), rather than (format t "~A" string).
  554.  
  555. Miscellaneous:
  556.  
  557.   * Be careful of circular lists and shared list structure. 
  558.  
  559.   * Watch out for macro redefinitions.
  560.  
  561.   * If you use (SETF (SYMBOL-FUNCTION 'foo) ...) to change the definition of
  562.     a built-in Lisp function named FOO, be aware that this may not work
  563.     correctly (i.e., as desired) in compiled code in all Lisps. In some Lisps, 
  564.     the compiler treats certain symbols in the LISP package specially,
  565.     ignoring the function definition.
  566.  
  567.   * A NOTINLINE may be needed if you want SETF of SYMBOL-FUNCTION to
  568.     affect calls within a file.  (See CLtL2, page 686.)
  569.  
  570.   * When dividing two numbers, beware of creating a rational number where
  571.     you intended to get an integer or floating point number. Use TRUNCATE
  572.     or ROUND to get an integer and FLOAT to ensure a floating point
  573.     number. This is a major source of errors when porting ZetaLisp or C
  574.     code to Common Lisp.
  575.  
  576.   * If your code doesn't work because all the symbols are mysteriously
  577.     in the keyword package, one of your comments has a colon (:) in
  578.     it instead of a semicolon (;).
  579.  
  580. ----------------------------------------------------------------
  581. [3-12] When is it right to use EVAL?
  582.  
  583. Hardly ever.  Any time you think you need to use EVAL, think hard about it.
  584. EVAL is useful when implementing a facility that provides an external
  585. interface to the Lisp interpreter.  For instance, many Lisp-based editors
  586. provide a command that prompts for a form and displays its value.
  587. Inexperienced macro writers often assume that they must explicitly EVAL the
  588. subforms that are supposed to be evaluated, but this is not so; the correct
  589. way to write such a macro is to have it expand into another form that has
  590. these subforms in places that will be evaluated by the normal evaluation
  591. rules.  Explicit use of EVAL in a macro is likely to result in one of two
  592. problems: the dreaded "double evaluation" problem, which may not show up
  593. during testing if the values of the expressions are self-evaluating
  594. constants (such as numbers); or evaluation at compile time rather than
  595. runtime.  For instance, if Lisp didn't have IF and one desired to write it,
  596. the following would be wrong:
  597.  
  598.    (defmacro if (test then-form &optional else-form)
  599.      ;; this evaluates all the subforms at compile time, and at runtime
  600.      ;; evaluates the results again.
  601.      `(cond (,(eval test) ,(eval then-form))
  602.             (t ,(eval else-form))))
  603.  
  604.    (defmacro if (test then-form &optional else-form)
  605.      ;; this double-evaluates at run time
  606.      `(cond ((eval ,test) (eval ,then-form))
  607.             (t (eval ,else-form)))
  608.  
  609. This is correct:
  610.  
  611.    (defmacro if (test then-form &optional else-form)
  612.      `(cond (,test ,then-form)
  613.             (t ,else-form)))
  614.  
  615. On the other hand, EVAL can sometimes be necessary when the only portable
  616. interface to an operation is a macro. 
  617.  
  618. ----------------------------------------------------------------
  619. [3-13] Why does my program's behavior change each time I use it?
  620.  
  621. Most likely your program is altering itself, and the most common way this
  622. may happen is by performing destructive operations on embedded constant
  623. data structures.  For instance, consider the following:
  624.  
  625.    (defun one-to-ten-except (n)
  626.      (delete n '(1 2 3 4 5 6 7 8 9 10)))
  627.    (one-to-ten-except 3) => (1 2 4 5 6 7 8 9 10)
  628.    (one-to-ten-except 5) => (1 2 4 6 7 8 9 10) ; 3 is missing
  629.  
  630. The basic problem is that QUOTE returns its argument, *not* a copy of
  631. it. The list is actually a part of the lambda expression that is in
  632. ONE-TO-TEN-EXCEPT's function cell, and any modifications to it (e.g., by
  633. DELETE) are modifications to the actual object in the function definition.
  634. The next time that the function is called, this modified list is used.
  635.  
  636. In some implementations calling ONE-TO-TEN-EXCEPT may even result in
  637. the signalling of an error or the complete aborting of the Lisp process.  Some
  638. Lisp implementations put self-evaluating and quoted constants onto memory
  639. pages that are marked read-only, in order to catch bugs such as this.
  640. Details of this behavior may vary even within an implementation,
  641. depending on whether the code is interpreted or compiled (perhaps due to
  642. inlined DEFCONSTANT objects).
  643.  
  644. All of these behaviors are allowed by the draft ANSI Common Lisp
  645. specification, which specifically states that the consequences of modifying
  646. a constant are undefined (X3J13 vote CONSTANT-MODIFICATION:DISALLOW).
  647.  
  648. To avoid these problems, use LIST to introduce a list, not QUOTE. QUOTE
  649. should be used only when the list is intended to be a constant which
  650. will not be modified.  If QUOTE is used to introduce a list which will
  651. later be modified, use COPY-LIST to provide a fresh copy.
  652.  
  653. For example, the following should all work correctly:
  654.  
  655.    o  (remove 4 (list 1 2 3 4 1 3 4 5))
  656.    o  (remove 4 '(1 2 3 4 1 3 4 5))   ;; Remove is non-destructive.
  657.    o  (delete 4 (list 1 2 3 4 1 3 4 5))
  658.    o  (let ((x (list 1 2 4 1 3 4 5)))
  659.         (delete 4 x))
  660.    o  (defvar *foo* '(1 2 3 4 1 3 4 5))
  661.       (delete 4 (copy-list *foo*))
  662.       (remove 4 *foo*)
  663.       (let ((x (copy-list *foo*)))
  664.          (delete 4 x))
  665.  
  666. The following, however, may not work as expected:
  667.  
  668.    o  (delete 4 '(1 2 3 4 1 3 4 5))
  669.      
  670. ----------------------------------------------------------------
  671. [3-14]  When producing formatted output in Lisp, where should you put the
  672.         newlines (e.g., before or after the line, FRESH-LINE vs TERPRI,
  673.         ~& vs ~% in FORMAT)?
  674.  
  675.  
  676. Where possible, it is desirable to write functions that produce output
  677. as building blocks. In contrast with other languages, which either
  678. conservatively force a newline at various times or require the program
  679. to keep track of whether it needs to force a newline, the Lisp I/O
  680. system keeps track of whether the most recently printed character was
  681. a newline or not. The function FRESH-LINE outputs a newline only if
  682. the stream is not already at the beginning of a line.  TERPRI forces a
  683. newline irrespective of the current state of the stream. These
  684. correspond to the ~& and ~% FORMAT directives, respectively. (If the
  685. Lisp I/O system can't determine whether it's physically at the
  686. beginning of a line, it assumes that a newline is needed, just in case.)
  687.  
  688. Thus, if you want formatted output to be on a line of its own, start
  689. it with ~& and end it with ~%. (Some people will use a ~& also at the
  690. end, but this isn't necessary, since we know a priori that we're not
  691. at the beginning of a line. The only exception is when ~& follows a
  692. ~A, to prevent a double newline when the argument to the ~A is a
  693. formatted string with a newline at the end.) For example, the
  694. following routine prints the elements of a list, N elements per line,
  695. and then prints the total number of elements on a new line:
  696.  
  697.    (defun print-list (list &optional (elements-per-line 10))
  698.      (fresh-line)
  699.      (loop for i upfrom 1
  700.            for element in list do
  701.        (format t "~A ~:[~;~%~]" element (zerop (mod i elements-per-line))))
  702.      (format t "~&~D~%" (length list)))
  703.  
  704. ----------------------------------------------------------------
  705. [3-15] I'm using DO to do some iteration, but it doesn't terminate. 
  706.  
  707. Your code probably looks something like
  708.    (do ((sublist list (cdr list))
  709.         ..)
  710.        ((endp sublist)
  711.         ..)
  712.      ..)
  713. or maybe
  714.    (do ((index start (+ start 2))
  715.         ..)
  716.        ((= index end)
  717.         ..)
  718.      ..)
  719.  
  720. The problem is caused by the (cdr list) and the (+ start 2) in the
  721. first line. You're using the original list and start index instead of
  722. the working sublist or index. Change them to (cdr sublist) and 
  723. (+ index 2) and your code should start working.
  724.  
  725. ----------------------------------------------------------------
  726. ;;; *EOF*
  727.